from flask import Blueprint, request, jsonify
from werkzeug.exceptions import BadRequest
from app import db
from app.favorites.models import Favorite
from app.favorites.schemas import favorite_schema, favorites_schema
from app.recipes.models import Recipe

# 创建收藏模块的蓝图
favorites_bp = Blueprint('favorites', __name__)

@favorites_bp.route('/', methods=['GET'])
def get_favorites():
    """
    获取所有收藏列表
    ---
    响应：收藏列表
    """
    favorites = Favorite.query.all()
    return jsonify(favorites_schema.dump(favorites))

@favorites_bp.route('/<int:favorite_id>', methods=['GET'])
def get_favorite(favorite_id):
    """
    获取单个收藏的详细信息
    ---
    参数：favorite_id - 收藏ID
    响应：收藏详细信息
    """
    favorite = Favorite.query.get_or_404(favorite_id)
    return jsonify(favorite_schema.dump(favorite))

@favorites_bp.route('/', methods=['POST'])
def create_favorite():
    """
    创建新收藏
    ---
    请求体：收藏信息（用户ID和食谱ID）
    响应：创建成功的收藏信息
    """
    data = request.get_json()
    
    if not data:
        raise BadRequest('No input data provided')
    
    # 验证必填字段
    required_fields = ['user_id', 'recipe_id']
    for field in required_fields:
        if field not in data:
            raise BadRequest(f'Missing required field: {field}')
    
    # 检查食谱是否存在
    recipe = Recipe.query.get(data['recipe_id'])
    if not recipe:
        raise BadRequest(f'Recipe not found: {data["recipe_id"]}')
    
    # 检查是否已经收藏
    existing_favorite = Favorite.query.filter_by(
        user_id=data['user_id'], 
        recipe_id=data['recipe_id']
    ).first()
    
    if existing_favorite:
        raise BadRequest('Recipe already favorited by this user')
    
    # 创建收藏对象
    favorite = Favorite(
        user_id=data['user_id'],
        recipe_id=data['recipe_id']
    )
    
    db.session.add(favorite)
    db.session.commit()
    
    return jsonify(favorite_schema.dump(favorite)), 201

@favorites_bp.route('/<int:favorite_id>', methods=['DELETE'])
def delete_favorite(favorite_id):
    """
    删除收藏
    ---
    参数：favorite_id - 收藏ID
    响应：成功删除的消息
    """
    favorite = Favorite.query.get_or_404(favorite_id)
    
    db.session.delete(favorite)
    db.session.commit()
    
    return jsonify({'message': 'Favorite deleted successfully'})

@favorites_bp.route('/user/<int:user_id>', methods=['GET'])
def get_favorites_by_user(user_id):
    """
    获取指定用户的所有收藏
    ---
    参数：user_id - 用户ID
    响应：收藏列表（包含食谱信息）
    """
    favorites = Favorite.query.filter_by(user_id=user_id).order_by(Favorite.created_at.desc()).all()
    return jsonify(favorites_schema.dump(favorites))

@favorites_bp.route('/recipe/<int:recipe_id>/count', methods=['GET'])
def get_favorite_count_by_recipe(recipe_id):
    """
    获取指定食谱的收藏数量
    ---
    参数：recipe_id - 食谱ID
    响应：收藏数量
    """
    recipe = Recipe.query.get_or_404(recipe_id)
    count = Favorite.query.filter_by(recipe_id=recipe_id).count()
    return jsonify({'count': count})

@favorites_bp.route('/user/<int:user_id>/count', methods=['GET'])
def get_favorite_count_by_user(user_id):
    """
    获取指定用户的收藏总数
    ---
    参数：user_id - 用户ID
    响应：收藏总数
    """
    # 检查用户是否存在
    from app.auth.models import User
    user = User.query.get(user_id)
    if not user:
        raise BadRequest(f'User not found: {user_id}')
    
    count = Favorite.query.filter_by(user_id=user_id).count()
    
    return jsonify({
        'user_id': user_id,
        'count': count
    })

@favorites_bp.route('/check', methods=['GET'])
def check_favorite():
    """
    检查用户是否收藏了某个食谱
    ---
    参数：user_id - 用户ID，recipe_id - 食谱ID
    响应：是否收藏的状态
    """
    user_id = request.args.get('user_id', type=int)
    recipe_id = request.args.get('recipe_id', type=int)
    
    if not user_id or not recipe_id:
        raise BadRequest('Missing required parameters: user_id and recipe_id')
    
    favorite = Favorite.query.filter_by(
        user_id=user_id, 
        recipe_id=recipe_id
    ).first()
    
    return jsonify({'is_favorited': favorite is not None})

@favorites_bp.route('/remove', methods=['DELETE'])
def remove_favorite_by_ids():
    """
    根据用户ID和食谱ID删除收藏
    ---
    参数：user_id - 用户ID，recipe_id - 食谱ID
    响应：成功删除的消息
    """
    data = request.get_json()
    
    if not data:
        raise BadRequest('No input data provided')
    
    user_id = data.get('user_id')
    recipe_id = data.get('recipe_id')
    
    if not user_id or not recipe_id:
        raise BadRequest('Missing required fields: user_id and recipe_id')
    
    favorite = Favorite.query.filter_by(
        user_id=user_id, 
        recipe_id=recipe_id
    ).first()
    
    if not favorite:
        raise BadRequest('Favorite not found')
    
    db.session.delete(favorite)
    db.session.commit()
    
    return jsonify({'message': 'Favorite removed successfully'})